<template>
  <div class="health-records">
    <van-nav-bar
      title="健康记录"
      left-arrow
      @click-left="router.back()"
    >

    </van-nav-bar>

    <!-- 记录类型切换 -->
    <van-tabs v-model:active="activeType" sticky @change="handleTypeChange">
      <van-tab name="all" title="全部" />
      <van-tab name="1" title="血压" />
      <van-tab name="2" title="血糖" />
      <van-tab name="3" title="体重" />
      <van-tab name="4" title="体温" />
    </van-tabs>

    <!-- 记录列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="record-item" v-for="item in list" :key="item.id">
          <div class="record-info">
            <div class="record-type">
              {{ getTypeName(item.recordType) }} :   {{ item.recordValue }}
            </div>
            <div class="record-time">
              {{ formatDateTime(item.measureTime) }}
            </div>
            <div class="record-remark" v-if="item.remark">
              备注：{{ item.remark }}
            </div>
          </div>
          <van-icon
            name="delete"
            class="delete-icon"
            @click="handleDelete(item.id)"
          />
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 添加记录按钮 -->
    <van-button
      class="add-btn"
      type="primary"
      icon="plus"
      round
      @click="router.push('/health/daily')"
    >
      添加记录
    </van-button>

    <!-- 导出弹窗 -->
    <van-popup
      v-model:show="showExportPopup"
      position="bottom"
      round
    >
      <div class="export-popup">
        <div class="popup-title">导出记录</div>
        <van-form>
          <van-field
            v-model="exportForm.startDate"
            label="开始日期"
            readonly
            @click="showStartDatePicker = true"
          />
          <van-field
            v-model="exportForm.endDate"
            label="结束日期"
            readonly
            @click="showEndDatePicker = true"
          />
          <van-field
            v-model="exportForm.type"
            label="记录类型"
            readonly
            is-link
            @click="showTypePicker = true"
          />
        </van-form>
        <div class="popup-buttons">
          <van-button block type="primary" @click="handleExport">
            导出记录
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 健康报告弹窗 -->
    <van-popup
      v-model:show="showReport"
      position="bottom"
      round
      style="height: 80vh"
    >
      <div class="report-popup">
        <div class="popup-title">健康报告</div>
        <div class="report-content" v-if="reportData">
          <!-- 血压数据 -->
          <div class="report-item" v-if="reportData.averageValues.bloodPressure">
            <div class="item-title">血压情况</div>
            <div class="item-stats">
              <div class="stat">
                <div class="label">平均值</div>
                <div class="value">{{ reportData.averageValues.bloodPressure }}</div>
              </div>
              <div class="stat">
                <div class="label">最高值</div>
                <div class="value">{{ reportData.maxValues.bloodPressure }}</div>
              </div>
              <div class="stat">
                <div class="label">最低值</div>
                <div class="value">{{ reportData.minValues.bloodPressure }}</div>
              </div>
            </div>
            <div class="trend-chart">
              <trend-chart :data="reportData.trends.bloodPressure" />
            </div>
          </div>

          <!-- 血糖数据 -->
          <div class="report-item" v-if="reportData.averageValues.bloodSugar">
            <!-- 类似血压的结构 -->
          </div>

          <!-- 体重数据 -->
          <div class="report-item" v-if="reportData.averageValues.weight">
            <!-- 类似血压的结构 -->
          </div>

          <!-- 体温数据 -->
          <div class="report-item" v-if="reportData.averageValues.temperature">
            <!-- 类似血压的结构 -->
          </div>

          <!-- 健康分析 -->
          <div class="analysis">
            <div class="analysis-title">健康建议</div>
            <div class="analysis-content">{{ reportData.analysis }}</div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup
      v-model:show="showStartDatePicker"
      position="bottom"
    >
      <van-datetime-picker
        type="date"
        title="选择开始日期"
        :min-date="new Date(2020, 0, 1)"
        :max-date="new Date()"
        @confirm="onStartDateConfirm"
        @cancel="showStartDatePicker = false"
      />
    </van-popup>

    <van-popup
      v-model:show="showEndDatePicker"
      position="bottom"
    >
      <van-datetime-picker
        type="date"
        title="选择结束日期"
        :min-date="new Date(2020, 0, 1)"
        :max-date="new Date()"
        @confirm="onEndDateConfirm"
        @cancel="showEndDatePicker = false"
      />
    </van-popup>

    <!-- 类型选择器 -->
    <van-popup
      v-model:show="showTypePicker"
      position="bottom"
    >
      <van-picker
        :columns="typeColumns"
        @confirm="onTypeConfirm"
        @cancel="showTypePicker = false"
        show-toolbar
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import {
  getHealthRecordsList,
  deleteHealthRecord,
  exportHealthRecords,
  exportHealthReport,
  getHealthReport
} from '@/api/health'
import { formatDateTime } from '@/utils/format'
import TrendChart from './components/TrendChart.vue'

const router = useRouter()
const route = useRoute()
const activeType = ref('all')
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const current = ref(1)
const size = ref(10)
const list = ref([])
const showExportPopup = ref(false)
const showReport = ref(false)
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)
const showTypePicker = ref(false)
const exportForm = ref({
  startDate: '',
  endDate: '',
  type: '全部'
})
const reportData = ref(null)

const reportTypes = [
  { key: 'bloodPressure', name: '血压', unit: 'mmHg' },
  { key: 'bloodSugar', name: '血糖', unit: 'mmol/L' },
  { key: 'weight', name: '体重', unit: 'kg' },
  { key: 'temperature', name: '体温', unit: '℃' }
]

const typeColumns = [
  { text: '全部', value: '' },
  { text: '血压', value: '1' },
  { text: '血糖', value: '2' },
  { text: '体重', value: '3' },
  { text: '体温', value: '4' }
]

// 根据类型获取单位
const getUnit = (type) => {
  switch (type) {
    case 1: return 'mmHg'
    case 2: return 'mmol/L'
    case 3: return 'kg'
    case 4: return '℃'
    default: return ''
  }
}

// 获取类型名称
const getTypeName = (type) => {
  const typeMap = {
    1: '血压',
    2: '血糖',
    3: '体重',
    4: '体温'
  }
  return typeMap[type] || '未知'
}

// 加载记录列表
const onLoad = async () => {
  try {
    loading.value = true
    const res = await getHealthRecordsList({
      current: current.value,
      size: size.value,
      type: activeType.value === 'all' ? null : Number(activeType.value)
    })

    if (refreshing.value) {
      list.value = []
      refreshing.value = false
    }

    list.value.push(...res.data.records)

    if (list.value.length >= res.data.total) {
      finished.value = true
    } else {
      current.value++
    }
  } catch (error) {
    showToast('加载失败')
  } finally {
    loading.value = false
  }
}

// 刷新
const onRefresh = () => {
  finished.value = false
  current.value = 1
  onLoad()
}

// 切换类型
const handleTypeChange = () => {
  list.value = []
  finished.value = false
  current.value = 1
  onLoad()
}

// 删除记录
const handleDelete = (id) => {
  showDialog({
    title: '提示',
    message: '确定要删除这条记录吗？',
    showCancelButton: true
  }).then(async () => {
    try {
      await deleteHealthRecord(id)
      showToast('删除成功')
      // 重新加载列表
      current.value = 1
      list.value = []
      finished.value = false
      onLoad()
    } catch (error) {
      showToast('删除失败')
    }
  })
}

// 导出相关
const handleExport = async () => {
  try {
    showToast({
      message: '正在导出...',
      duration: 0,
      forbidClick: true,
    })

    const params = {
      type: exportForm.value.type === '全部' ? '' : exportForm.value.type,
      startDate: exportForm.value.startDate,
      endDate: exportForm.value.endDate
    }

    const response = await exportHealthRecords(params)

    // 获取文件名
    const contentDisposition = response.headers['content-disposition']
    let fileName = '健康记录.xlsx'
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename\*=utf-8''(.+)/)
      if (fileNameMatch) {
        fileName = decodeURIComponent(fileNameMatch[1])
      }
    }

    // 创建Blob对象
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // 创建下载链接
    const downloadLink = document.createElement('a')
    downloadLink.href = URL.createObjectURL(blob)
    downloadLink.download = fileName

    // 触发下载
    document.body.appendChild(downloadLink)
    downloadLink.click()
    document.body.removeChild(downloadLink)

    // 清理URL对象
    URL.revokeObjectURL(downloadLink.href)

    showToast.clear()
    showToast('导出成功')
    showExportPopup.value = false
  } catch (error) {
    showToast.clear()
    showToast('导出失败')
  }
}

// 加载健康报告数据
const loadReport = async () => {
  try {
    loading.value = true
    const { data } = await getHealthReport({
      startDate: exportForm.value.startDate,
      endDate: exportForm.value.endDate
    })
    reportData.value = data
  } catch (error) {
    console.error('获取报告失败:', error)
    showToast('获取报告失败')
  } finally {
    loading.value = false
  }
}

// 监听报告弹窗显示
watch(showReport, (val) => {
  if (val) {
    loadReport()
  }
})

// 日期选择处理
const onStartDateConfirm = (date) => {
  exportForm.value.startDate = formatDateTime(date)
  showStartDatePicker.value = false
}

const onEndDateConfirm = (date) => {
  exportForm.value.endDate = formatDateTime(date)
  showEndDatePicker.value = false
}

// 类型选择处理
const onTypeConfirm = (value) => {
  exportForm.value.type = value.text
  showTypePicker.value = false
}

onMounted(() => {
  // 如果有查询参数type，设置activeType
  const type = route.query.type
  if (type) {
    activeType.value = type
  }
  onLoad()
})
</script>

<style lang="scss" scoped>
.health-records {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 80px;

  .record-item {
    margin: 12px;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .record-info {
      flex: 1;

      .record-type {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
      }

      .record-value {
        font-size: 20px;
        color: #1989fa;
        margin-bottom: 8px;
      }

      .record-time {
        font-size: 12px;
        color: #999;
        margin-bottom: 4px;
      }

      .record-remark {
        font-size: 14px;
        color: #666;
      }
    }

    .delete-icon {
      color: #ee0a24;
      font-size: 18px;
      padding: 4px;
    }
  }

  .add-btn {
    position: fixed;
    right: 16px;
    bottom: 100px;
    z-index: 100;
    padding: 0 20px;
    height: 40px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .nav-right {
    display: flex;
    gap: 16px;
  }

  .export-popup,
  .report-popup {
    padding: 16px;

    .popup-title {
      font-size: 18px;
      font-weight: 500;
      text-align: center;
      margin-bottom: 16px;
    }

    .popup-buttons {
      margin-top: 16px;
    }
  }

  .report-content {
    .report-item {
      margin-bottom: 24px;

      .item-title {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 12px;
      }

      .item-stats {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
        margin-bottom: 16px;

        .stat {
          text-align: center;

          .label {
            font-size: 12px;
            color: #666;
          }

          .value {
            font-size: 18px;
            color: #1989fa;
            font-weight: 500;
          }
        }
      }

      .trend-chart {
        height: 200px;
      }
    }

    .analysis {
      .analysis-title {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 12px;
      }

      .analysis-content {
        line-height: 1.6;
        color: #666;
        white-space: pre-line;
      }
    }
  }
}
</style>
